<template>
  <el-row :gutter="20">
    <el-col :span="18">
      <ContentWrap title="申请信息">
        <el-form
          ref="formRef"
          v-loading="formLoading"
          :model="formData"
          :rules="formRules"
          label-width="80px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-row :gutter="10">
                  <el-col :span="14">
                    <el-date-picker
                      v-model="formData.startTime"
                      type="date"
                      value-format="YYYY-MM-DD"
                      placeholder="选择日期"
                      style="width: 100%"
                    />
                  </el-col>
                  <el-col :span="10">
                    <el-time-select
                      v-model="formData.startHour"
                      start="00:00"
                      step="00:10"
                      end="23:50"
                      placeholder="选择时间"
                      style="width: 100%"
                    />
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="endTime">
                <el-row :gutter="10">
                  <el-col :span="14">
                    <el-date-picker
                      v-model="formData.endTime"
                      type="date"
                      value-format="YYYY-MM-DD"
                      placeholder="选择日期"
                      style="width: 100%"
                    />
                  </el-col>
                  <el-col :span="10">
                    <el-time-select
                      v-model="formData.endHour"
                      start="00:00"
                      step="00:10"
                      end="23:50"
                      placeholder="选择时间"
                      style="width: 100%"
                    />
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="出差时长" prop="duration">
                <el-input v-model="formData.duration" placeholder="自动计算（小时）" disabled>
                  <template #append>小时</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出差地点" prop="destination">
                <el-input v-model="formData.destination" placeholder="请输入出差地点" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="交通工具" prop="transportation">
                <el-input v-model="formData.transportation" placeholder="请输入交通工具" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预算金额" prop="budgetAmount">
                <el-input-number v-model="formData.budgetAmount" :step="100" :placeholder="'请输入预算金额'" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="同行人员" prop="accompanyPersons">
                <UserSelectMultiple
                  v-model="formData.accompanyPersons"
                  @node-change="onAccompanyPersonsChange"
                />
              </el-form-item>
            </el-col> -->
            <!-- <el-col :span="12">
              <el-form-item label="同行人员姓名">
                <el-input v-model="formData.accompanyPersonsNames" placeholder="自动生成" disabled />
              </el-form-item>
            </el-col> -->
          <!-- </el-row> -->
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="出差事由" prop="tripReason">
                <el-input v-model="formData.tripReason" placeholder="请输入出差事由" :rows="5" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="文件附件">
                <OaFileManager :folderDisabled="true" @fileSelectSuccess="fileSelectScccess" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item>
                <el-button :disabled="formLoading" type="primary" @click="submitForm">
                  确 定
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </ContentWrap>
    </el-col>

    <!-- 右侧审批流程 -->
    <el-col :span="6">
      <ContentWrap title="审批流程" :bodyStyle="{ padding: '0 20px 0' }">
        <ProcessInstanceTimeline
          ref="timelineRef"
          :activity-nodes="activityNodes"
          :show-status-icon="false"
          @select-user-confirm="selectUserConfirm"
        />
      </ContentWrap>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import { BusinessTripApplyApi, BusinessTripApplyVO } from '@/api/oa/businesstripapply'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useUserStore } from '@/store/modules/user'

// 审批相关：import
import * as DefinitionApi from '@/api/bpm/definition'
import ProcessInstanceTimeline from '@/views/bpm/processInstance/detail/ProcessInstanceTimeline.vue'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { CandidateStrategy, NodeId } from '@/components/SimpleProcessDesignerV2/src/consts'
import { ApprovalNodeInfo } from '@/api/bpm/processInstance'
import UserSelectMultiple from '@/views/system/user/UserSelectMultiple.vue'
import dayjs from 'dayjs'
import { OvertimeApplyApi, OvertimeApplyVO, OvertimeDurationCalcReqVO, OvertimeDurationCalcRespVO } from '@/api/oa/overtimeapply'
import OaFileManager from '@/components/Oa/OaFileManager.vue'

defineOptions({ name: 'OaBusinessTripApplyCreate' })

const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由
const userStore = useUserStore() // 用户信息

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const formData = ref<{
  startTime: string | undefined
  startHour: string | undefined
  endTime: string | undefined
  endHour: string | undefined
  duration: number | undefined
  destination: string | undefined
  tripReason: string | undefined
  transportation: string | undefined
  budgetAmount: number | undefined
  accompanyPersons: any | undefined
  accompanyPersonsNames: string
  appendix: string | undefined
  status: number | undefined
  files: string | undefined
  startType?: number
  endType?: number
}>({
  startTime: undefined,
  startHour: '09:00', // 默认9点
  endTime: undefined,
  endHour: '18:00', // 默认18点
  duration: undefined,
  destination: undefined,
  tripReason: undefined,
  transportation: undefined,
  budgetAmount: undefined,
  accompanyPersons: undefined,
  accompanyPersonsNames: '',
  appendix: undefined,
  status: undefined,
  files: undefined
})
const formRef = ref() // 表单 Ref

// 审批相关：变量
const processDefineKey = 'oa_business_trip_apply' // 流程定义 Key
const startUserSelectTasks = ref([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref({}) // 发起人选择审批人的数据
const tempStartUserSelectAssignees = ref({}) // 历史发起人选择审批人的数据，用于每次表单变更时，临时保存
const activityNodes = ref<ProcessInstanceApi.ApprovalNodeInfo[]>([]) // 审批节点信息
const processDefinitionId = ref('')

/** 提交表单 */
const submitForm = async () => {
  // 1.1 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 1.2 审批相关：校验指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    for (const userTask of startUserSelectTasks.value) {
      if (
        Array.isArray(startUserSelectAssignees.value[userTask.id]) &&
        startUserSelectAssignees.value[userTask.id].length === 0
      ) {
        return message.warning(`请选择\${userTask.name}的审批人`)
      }
    }
  }

  // 2. 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as BusinessTripApplyVO
    // 审批相关：设置指定审批人
    if (startUserSelectTasks.value?.length > 0) {
      data.startUserSelectAssignees = startUserSelectAssignees.value
    }
    await BusinessTripApplyApi.createBusinessTripApply(data)
    message.success('发起成功')
    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ name: 'BusinessTripApply' })
  } finally {
    formLoading.value = false
  }
}
const fileSelectScccess = (fileIds: string[]) => {
  formData.value.files = fileIds.join(',')
}

/** 审批相关：获取审批详情 */
const getApprovalDetail = async () => {
  try {
    const data = await ProcessInstanceApi.getApprovalDetail({
      processDefinitionId: processDefinitionId.value,
      // TODO 小北：可以支持 processDefinitionKey 查询
      activityId: NodeId.START_USER_NODE_ID,
      processVariablesStr: JSON.stringify({ day: daysDifference() }) // 解决 GET 无法传递对象的问题，后端 String 再转 JSON
    })

    if (!data) {
      message.error('查询不到审批详情信息！')
      return
    }
    // 获取审批节点，显示 Timeline 的数据
    activityNodes.value = data.activityNodes

    // 获取发起人自选的任务
    startUserSelectTasks.value = data.activityNodes?.filter(
      (node: ApprovalNodeInfo) => CandidateStrategy.START_USER_SELECT === node.candidateStrategy
    )
    // 恢复之前的选择审批人
    if (startUserSelectTasks.value?.length > 0) {
      for (const node of startUserSelectTasks.value) {
        if (
          tempStartUserSelectAssignees.value[node.id] &&
          tempStartUserSelectAssignees.value[node.id].length > 0
        ) {
          startUserSelectAssignees.value[node.id] = tempStartUserSelectAssignees.value[node.id]
        } else {
          startUserSelectAssignees.value[node.id] = []
        }
      }
    }
  } finally {
  }
}

/** 审批相关：选择发起人 */
const selectUserConfirm = (id: string, userList: any[]) => {
  startUserSelectAssignees.value[id] = userList?.map((item: any) => item.id)
}

// 计算天数差
// TODO @小北：可以搞到 formatTime 里面去，然后看看 dayjs 里面有没有现成的方法，或者辅助计算的方法。
const daysDifference = () => {
  const oneDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
  const diffTime = Math.abs(Number(formData.value.endTime) - Number(formData.value.startTime))
  return Math.floor(diffTime / oneDay)
}

/** 初始化 */
onMounted(async () => {
  // TODO @小北：这里可以简化，统一通过 getApprovalDetail 处理么？
  const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
    undefined,
    processDefineKey
  )

  if (!processDefinitionDetail) {
    message.error('出差申请的流程模型未配置，请检查！')
    return
  }
  processDefinitionId.value = processDefinitionDetail.id
  startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks

  // 审批相关：加载最新的审批详情，主要用于节点预测
  await getApprovalDetail()
})

/** 审批相关：预测流程节点会因为输入的参数值而产生新的预测结果值，所以需重新预测一次, formData.value可改成实际业务中的特定字段 */
watch(
  formData.value,
  (newValue, oldValue) => {
    if (!oldValue) {
      return
    }
    if (newValue && Object.keys(newValue).length > 0) {
      // 记录之前的节点审批人
      tempStartUserSelectAssignees.value = startUserSelectAssignees.value
      startUserSelectAssignees.value = {}
      // 加载最新的审批详情,主要用于节点预测
      getApprovalDetail()
    }
  },
  {
    immediate: true
  }
)
// 监听开始和结束时间变化
watch(
  () => [formData.value.startTime, formData.value.startHour, formData.value.endTime, formData.value.endHour],
  async ([startDate, startHour, endDate, endHour]) => {
    if (startDate && startHour && endDate && endHour) {
      // 调用新接口计算时长（按24小时累计真实小时数）
      try {
        const hours = await BusinessTripApplyApi.calculateDurationByTime(
          startDate as string,
          startHour as string,
          endDate as string,
          endHour as string
        )
        formData.value.duration = hours // 赋值小时数
      } catch (error) {
        console.error('计算出差时长失败:', error)
      }
    }
  }
)
// const validateEndTime = (rule: any, value: any, callback: any) => {
//   if (!formData.value.startTime || !value) {
//     callback()
//     return
//   }
//   if (Number(value) < Number(formData.value.startTime)) {
//     callback(new Error('结束日期不能小于开始日期'))
//     return
//   }
//   if (value === formData.value.startTime && formData.value.endType && formData.value.startType && formData.value.endType <= formData.value.startType) {
//     callback(new Error('同一天时，结束时间类型必须晚于开始时间类型'))
//     return
//   }
//   callback()
// }

const formRules = reactive({
  startTime: [{ required: true, message: '开始日期不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束日期不能为空', trigger: 'blur' }],
  duration: [{ required: true, message: '出差时长不能为空', trigger: 'blur' }],
  tripReason: [{ required: true, message: '出差事由不能为空', trigger: 'blur' }],
})

 

</script>

<style lang="scss" scoped>
.text-danger {
  color: #f56c6c;
  font-weight: bold;
}

.text-success {
  color: #67c23a;
  font-weight: bold;
}

:deep(.el-table) {
  .el-table__row {
    .el-table__cell {
      padding: 8px 0;
    }
  }
}

:deep(.el-tag) {
  font-size: 12px;
  padding: 2px 6px;
}
</style>
